<?php
declare (strict_types = 1);

namespace app\controller\admin;

use think\facade\View;
use think\facade\Request;

use app\model\Menu as MenuModel;

class Menu extends Common
{
    public function index($act=null)
    {
        if ($act=='del') {
            if (!Request::isPost()) {
                return error(lang('参数错误'));
            }
            $ids = input('post.');

            if (!empty($ids)) {
                $r = MenuModel::destroy($ids['ids']);
                if ($r) {
                    add_log('删除菜单，ID：'.implode(',', $ids['ids']), $this->request->user->username);
                    return success(lang('操作成功'), (string) url('admin/menu/index'));
                }
            }

            return error(lang('请勾选需要删除的选项'));
        }

        if ($act=='update') {
            if (!Request::isPost()) {
                return error(lang('参数错误'));
            }
            $data = Request::only(['id'=>0,'pid'=>0,'url'=>'#','title'=>'','icon'=>'','tips'=>'','status'=>1,'o'=>0], 'post');

            if($data['id']>0){
              $menu = MenuModel::find($data['id']);
            }else{
              $menu = new MenuModel;
            }

            $menu->save($data);

            if ($data['id']==0) {
                add_log('新增菜单，ID:'.$menu->id, $this->request->user->username);
            } else {
                add_log('编辑菜单，ID:'.$menu->id, $this->request->user->username);
            }

            return success(lang('操作成功'), (string) url('admin/menu/index'));
        }

        if ($act=='edit') {
            $id = Request::param('id');
            $current = MenuModel::where(['id'=>$id])->find();
            if (!$current) {
                return error(lang('参数错误'));
            }

            $list = MenuModel::field('id,pid,title')
                    ->where(['status'=>1])
                    ->order('o ASC')
                    ->select()
                    ->toArray();
            $list = categorize_and_sort_hierarchy($list);

            View::assign('current', $current);
            View::assign('list', $list);
            View::assign('id', $id);
            return View::fetch('form');
        }

        if ($act=='add') {
            $list = MenuModel::field('id,pid,title')->where(['status'=>1])->order('o ASC')->select()->toArray();;
            $list = categorize_and_sort_hierarchy($list);
            View::assign('list', $list);

            return View::fetch('form');
        }

        $list = MenuModel::field('id,pid,url,title,icon,status,o')->order('o ASC')->select()->toArray();
        $list = categorize_and_sort_hierarchy($list);
        View::assign('list', $list);
        return View::fetch();
    }
}
